package titt.server.func;

import titt.head.HeadFactory;
import titt.head.request.MethodHead;
import titt.head.response.ResponseHead;
import titt.io.socket.TITTSocket;
import titt.key.TITTKey;
import titt.server.os.ObjectServer;
import titt.server.service.Service;

public class ServiceErrorDetection implements TITTFunction {

	public String getMethodName() {
		return "error";
	}

	public void handle(TITTKey key, MethodHead head, TITTSocket ts, ObjectServer os) throws Exception {
		
		String serviceID = head.getParams()[0].getObject();
		
		Service s = os.getServerDatabase().get(serviceID);

		if(s == null) {

			ts.getHeadWriter().writeHead(new ResponseHead(404, HeadFactory.EMPTY));
			ts.close();
			
			return;
		}
//		System.out.println("ERROR DETECTION FOR " + serviceID);
		ts.setTimeout(0);
		
		s.addDependency(ts);
		
		try {
			while(ts.getInputStream().asStream().read() != -1);

		}
		catch(Exception e) {
//			System.out.println("[timeout] " + key.asKeyString());
		}
//		System.out.println("BREAKING " + serviceID);
		if(!ts.isClosed())
			ts.close();
		
		os.getServerInternal().unregister(serviceID, 0);

	}

}
